package com.smart.community.user.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.feign.property.service.IUserPropertyCompanyFeign;
import com.smart.community.user.dto.LoginLogQueryDTO;
import com.smart.community.user.entity.LoginLog;
import com.smart.community.user.mapper.LoginLogMapper;
import com.smart.community.user.service.LoginLogService;

/**
 * 登录日志服务实现类
 *
 * @author Wu.Liang
 * @since 2025-07-05
 */
@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {

    private static final Logger log = LoggerFactory.getLogger(LoginLogServiceImpl.class);
    
    @Autowired
    private IUserPropertyCompanyFeign userPropertyCompanyFeign;
    @Autowired
    private DataScopeFeign dataScopeFeign;

    @Override
    public void recordLoginLog(Long userId, String username, String ipAddress, String userAgent, Integer status, String message) throws Exception {
        // 标准实现：记录登录日志
        LoginLog loginLog = new LoginLog();
        
        // 处理userId为null的情况，设置为0表示未知用户
        if (userId != null) {
            loginLog.setUserId(userId);
        } else {
            loginLog.setUserId(0L); // 设置为0表示未知用户
        }
        
        loginLog.setUsername(username != null ? username : "未知用户");
        loginLog.setLoginIp(ipAddress);
        
        // 优化browser字段处理，避免数据截断
        String browserInfo = parseBrowserInfo(userAgent);
        loginLog.setBrowser(browserInfo);
        
        loginLog.setLoginStatus(status);
        loginLog.setLoginMessage(message);
        loginLog.setLoginTime(LocalDateTime.now());
        loginLog.setStatus(1); // 默认状态
        loginLog.setCreateTime(LocalDateTime.now());
        loginLog.setUpdateTime(LocalDateTime.now());
        loginLog.setDeleted(0); // 未删除
        loginLog.setLoginType(1); // 默认登录类型：用户名密码
        loginLog.setOnlineDuration(0L); // 默认在线时长
        
        this.save(loginLog);
    }

    /**
     * 解析浏览器信息，提取关键信息避免数据截断
     * 
     * @param userAgent 用户代理字符串
     * @return 处理后的浏览器信息
     */
    private String parseBrowserInfo(String userAgent) {
        if (userAgent == null || userAgent.trim().isEmpty()) {
            return "未知浏览器";
        }
        
        try {
            // 如果userAgent长度超过100，进行智能截取
            if (userAgent.length() > 100) {
                // 提取浏览器名称
                String browser = "未知浏览器";
                if (userAgent.contains("Chrome")) {
                    browser = "Chrome";
                } else if (userAgent.contains("Firefox")) {
                    browser = "Firefox";
                } else if (userAgent.contains("Safari")) {
                    browser = "Safari";
                } else if (userAgent.contains("Edge")) {
                    browser = "Edge";
                } else if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                    browser = "Internet Explorer";
                } else if (userAgent.contains("Opera")) {
                    browser = "Opera";
                }
                
                // 提取操作系统信息
                String os = "未知系统";
                if (userAgent.contains("Windows")) {
                    os = "Windows";
                } else if (userAgent.contains("Mac")) {
                    os = "macOS";
                } else if (userAgent.contains("Linux")) {
                    os = "Linux";
                } else if (userAgent.contains("Android")) {
                    os = "Android";
                } else if (userAgent.contains("iOS")) {
                    os = "iOS";
                }
                
                return browser + " on " + os;
            }
            
            return userAgent;
        } catch (Exception e) {
            log.warn("解析浏览器信息失败: {}", e.getMessage());
            return "未知浏览器";
        }
    }

    @Override
    public List<LoginLog> getRecentLoginLogs(Long userId, Integer limit) throws Exception {
        // 标准实现：获取用户最近登录日志
        return new ArrayList<>();
    }
    
    @Override
    public PageResult<LoginLog> getLoginLogPage(LoginLogQueryDTO queryDTO) throws Exception {
        // 创建分页对象
        Page<LoginLog> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        
        // 执行分页查询
        IPage<LoginLog> pageResult = baseMapper.selectLoginLogPage(page, queryDTO);
        
        // 构建返回结果
        PageResult<LoginLog> result = new PageResult<>();
        result.setCurrent((int) pageResult.getCurrent());
        result.setSize((int) pageResult.getSize());
        result.setTotal(pageResult.getTotal());
        result.setPages((int) pageResult.getPages());
        result.setRecords(pageResult.getRecords());
        
        return result;
    }
    
    @Override
    public PageResult<LoginLog> getLoginLogPageWithPermission(LoginLogQueryDTO queryDTO) throws Exception {
        // 获取当前用户ID
        Long currentUserId = SecurityUtils.getCurrentUserId();
        try {
            // 1. 检查超级管理员权限
            Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
            if (isSuperAdmin) {
                // 超级管理员可以查看所有登录日志
                log.info("用户{}为超级管理员，可查看所有登录日志", currentUserId);
                return getLoginLogPage(queryDTO);
            }
            
            // 2. 获取用户数据权限范围
            DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(currentUserId);
            // 3. 根据权限范围过滤数据
            if (dataScopeInfo.isPropertyCompanyUser()) {
                // 通过Feign接口获取当前用户的物业公司ID
                try {
                	// 用户关联的所有物业公司ID
                	List<Long> propertyCompanyIds = dataScopeInfo.getPropertyCompanyIds();
                	List<Long> userIds = new ArrayList<>();
                	for (Long propertyCompanyId : propertyCompanyIds) {
                		List<Long> temp = userPropertyCompanyFeign.getUserIdsByPropertyCompanyId(propertyCompanyId);
                		userIds.addAll(temp);
                	}
                	// 获取当前用户能看到的最终获取所有用户ID
                	List<Long> collect = userIds.stream().distinct().collect(Collectors.toList());
                    if (collect != null && collect.size()>0) {
                        // 设置物业公司ID过滤条件
                        queryDTO.setUserIds(collect);
                        
                        // 创建分页对象
                        Page<LoginLog> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
                        
                        
                        // 执行分页查询
                		LambdaQueryWrapper<LoginLog> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.in(LoginLog::getUserId, queryDTO.getUserIds());
                        Page<LoginLog> page2 = this.page(page, queryWrapper);
                        
                        // 构建返回结果
                        return buildPageResult(page2);
                    } else {
                        return createEmptyPageResult(queryDTO);
                    }
                } catch (Exception e) {
                    log.warn("获取用户物业公司信息失败，用户ID：{}，错误：{}", currentUserId, e.getMessage());
                    return createEmptyPageResult(queryDTO);
                }
            } else {
                // 普通用户无权限查看登录日志
                log.info("用户{}为普通用户，无权限查看登录日志", currentUserId);
                return createEmptyPageResult(queryDTO);
            }
            
        } catch (Exception e) {
            log.error("数据权限验证失败，用户ID：{}，错误：{}", currentUserId, e.getMessage(), e);
            
            // 权限验证失败时，返回空结果，确保数据安全
            return createEmptyPageResult(queryDTO);
        }
    }
    
    /**
     * 创建空的分页结果
     * 
     * @param queryDTO 查询条件
     * @return 空的分页结果
     */
    private PageResult<LoginLog> createEmptyPageResult(LoginLogQueryDTO queryDTO) {
        PageResult<LoginLog> result = new PageResult<>();
        result.setCurrent(queryDTO.getCurrent());
        result.setSize(queryDTO.getSize());
        result.setTotal(0L);
        result.setPages(0);
        result.setRecords(new ArrayList<>());
        return result;
    }
    
    /**
     * 构建分页结果
     * 
     * @param pageResult MyBatis-Plus分页结果
     * @return 分页结果
     */
    private PageResult<LoginLog> buildPageResult(IPage<LoginLog> pageResult) {
        PageResult<LoginLog> result = new PageResult<>();
        result.setCurrent((int) pageResult.getCurrent());
        result.setSize((int) pageResult.getSize());
        result.setTotal(pageResult.getTotal());
        result.setPages((int) pageResult.getPages());
        result.setRecords(pageResult.getRecords());
        return result;
    }
    
    @Override
    public PageResult<LoginLog> getLoginLogByUserId(Long userId, Integer current, Integer size) throws Exception {
        // 创建分页对象
        Page<LoginLog> page = new Page<>(current, size);
        
        // 构建查询条件
        LoginLogQueryDTO queryDTO = new LoginLogQueryDTO();
        queryDTO.setCurrent(current);
        queryDTO.setSize(size);
        // 设置用户ID查询条件
        List<Long> userIds = new ArrayList<>();
        userIds.add(userId);
        queryDTO.setUserIds(userIds);
        
        // 执行分页查询
        IPage<LoginLog> pageResult = baseMapper.selectLoginLogPage(page, queryDTO);
        
        // 构建返回结果
        PageResult<LoginLog> result = new PageResult<>();
        result.setCurrent((int) pageResult.getCurrent());
        result.setSize((int) pageResult.getSize());
        result.setTotal(pageResult.getTotal());
        result.setPages((int) pageResult.getPages());
        result.setRecords(pageResult.getRecords());
        
        return result;
    }
    
    @Override
    public PageResult<LoginLog> getLoginLogByPropertyCompanyId(Long propertyCompanyId, Integer current, Integer size) throws Exception {
        // 创建分页对象
        Page<LoginLog> page = new Page<>(current, size);
        
        // 构建查询条件，只查询物业公司下用户的登录日志
        LoginLogQueryDTO queryDTO = new LoginLogQueryDTO();
        queryDTO.setCurrent(current);
        queryDTO.setSize(size);
        queryDTO.setPropertyCompanyId(propertyCompanyId);
        
        // 执行分页查询
        IPage<LoginLog> pageResult = baseMapper.selectLoginLogPage(page, queryDTO);
        
        // 构建返回结果
        PageResult<LoginLog> result = new PageResult<>();
        result.setCurrent((int) pageResult.getCurrent());
        result.setSize((int) pageResult.getSize());
        result.setTotal(pageResult.getTotal());
        result.setPages((int) pageResult.getPages());
        result.setRecords(pageResult.getRecords());
        
        return result;
    }
    
    @Override
    public IUserPropertyCompanyFeign getUserPropertyCompanyFeign() {
        return userPropertyCompanyFeign;
    }
} 